package projet1;

public class NodeStack<E>
{
    protected Node<E> top;
    protected int size;

    /*
     * Cree une nouvelle stack
     */
    public NodeStack()
    {
        top = null;
        size = 0;
    }
    
    /*
     * @post: Retourne la taille de la pile
     */
    public int size()
    {
        return size;
    }
    
    /*
     * @post: Retourne true si la pile est vide
     */
    public boolean isEmpty()
    {
        if (top == null)
        {
            return true;
        }
        return false;
    }

    /*
     * @pre: Rajoute l'element elem sur la pile
     */
    public void push(E elem)
    {
        Node<E> v = new Node<E>(elem, top);
        top = v;
        size++;
    }

    /*
     * @post: Retourne le noeud au dessus de la pile
     *        Lance une exception si la file est vide
     */
    public Node<E> top() throws EmptyStackException
    {
        if (isEmpty())
        {
            throw new EmptyStackException("Stack is empty");
        }
        return top;
    }

    /*
     * @post: Retire le dernier element de la pile
     *        Lance une exception si la file est vide
     */
    public E pop() throws EmptyStackException
    {
        if (isEmpty())
        {
            throw new EmptyStackException("Stack is empty");
        }
        E temp = top.getValue();
        top = top.getNext();
        size--;
        return temp;
    }
    
    @Override
    public String toString()
    {
        if(isEmpty())
        {
            return "Empty stack";
        }
        String text;
        Node<E> elem = top;
        text = top.getValue().toString();
        while(elem.getNext() != null)
        {
            elem = elem.getNext();
            text += ", "+elem.getValue().toString();
        }
        return text;
    }
}